﻿#region using

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

#endregion

namespace JupiterLibrary
{
    /// <summary>
    /// Representa un IndexBuffer...¡siempre de 32 bits!
    /// </summary>
    public class IB
    {
        public UInt32[] Indices;

        IndexBuffer indexBuffer;

        /// <summary>Informs the engine that this buffer is dirty and needs to update.</summary>
        public bool Dirty = true;

        public void Dispose()
        {
            if (indexBuffer != null)
            {
                indexBuffer.Dispose();

                indexBuffer = null;

            }
        }

        /// <summary>
        /// Binds the IndexBuffer to the device
        /// </summary>
        internal void SetToDevice()
        {
            Update();

            Jupiter.Video.GraphicsDevice.Indices = indexBuffer;

        }

        public void Update()
        {
            if (!Dirty) return;

            if (indexBuffer != null)
            {
                // Si cambia el tamaño del buffer, lo liberamos y creamos de nuevo
                if (Indices.Length != indexBuffer.IndexCount)
                    Dispose();
            }

            if (indexBuffer == null)
            {
                indexBuffer = new IndexBuffer(Jupiter.Video.GraphicsDevice, IndexElementSize.ThirtyTwoBits, Indices.Length, BufferUsage.WriteOnly);
            }

            Dirty = false;

            indexBuffer.SetData<UInt32>(Indices);

        }
    }

    /// <summary>
    /// Gestiona la colección de <see cref="IB"/>.
    /// </summary>
    internal class IndexBuffers
    {

        public List<IB> List;

        public IndexBuffers()
        {
            List = new List<IB>();
        }

        /// <summary>
        /// Dispose and removes the list elements
        /// </summary>
        public void Dispose()
        {
            foreach (IB ib in List)
            {
                ib.Dispose();
            }

            List.Clear();
        }

        public IB CreateAndAdd()
        {
            IB ib = new IB();

            List.Add(ib);

            return ib;
        }
    }
}

